<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="处方id" prop="id">
               <el-input
                   v-model="queryParams.id"
                   placeholder="处方id"
                   clearable
                   @keyup.enter.native="handleQuery"/>
            </el-form-item>
      <el-form-item label="患者名" prop="patientName">
        <!--        <el-input-->
        <!--            v-model="queryParams.patientName"-->
        <!--            placeholder="请输入患者名"-->
        <!--            clearable-->
        <!--            @keyup.enter.native="handleQuery"-->
        <!--        />-->
        <el-autocomplete
          popper-class="my-autocomplete"
          class="inline-input"
          v-model="queryParams.patientName"
          :fetch-suggestions="querySearchAsyncForPatient"
          placeholder="请输入患者姓名"
          @keyup.enter.native="handleQuery"
        ><i
          class="el-icon-edit el-input__icon"
          slot="suffix"
        >
        </i>
          <template slot-scope="{ item }">
            <div class="name">{{ item.value = item.name }}</div>
            <div class="idCard">{{ item.idCard }}</div>
          </template>
        </el-autocomplete>
      </el-form-item>
      <el-form-item label="医生名" prop="userName">
        <!--        <el-input-->
        <!--            v-model="queryParams.doctorName"-->
        <!--            placeholder="请输入医生名"-->
        <!--            clearable-->
        <!--            @keyup.enter.native="handleQuery"-->
        <!--        />-->
        <el-autocomplete
          popper-class="my-autocomplete"
          class="inline-input"
          v-model="queryParams.doctorName"
          :fetch-suggestions="querySearchAsync"
          placeholder="请输入医生姓名"
          @keyup.enter.native="handleQuery"
        ><i
          class="el-icon-edit el-input__icon"
          slot="suffix"
        >
        </i>
          <template slot-scope="{ item }">
            <div class="name">{{ item.value = item.userName }}</div>
            <div class="idCard">{{ item.idCard }}</div>
          </template>
        </el-autocomplete>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['prescription:prescription:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['prescription:prescription:edit']"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['prescription:prescription:remove']"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['prescription:prescription:export']"
        >导出
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="prescriptionList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="处方id" align="center" prop="id"/>
      <el-table-column label="患者名" align="center" prop="patientName"/>
      <el-table-column label="医生名" align="center" prop="doctorName"/>
      <el-table-column label="药品列表" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleLandClick(scope.row)"
            v-hasPermi="['prescription:prescription:edit']"
          >详情
          </el-button>
        </template>
      </el-table-column>
      <!-- <el-table-column label="药品id数组列表" align="center" prop="drugList" /> -->
      <el-table-column label="处方信息" align="center" prop="prescriptionInfo"/>
      <el-table-column label="用法说明" align="center" prop="prescriptionUsage"/>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['prescription:prescription:edit']"
          >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['prescription:prescription:remove']"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加处方管理对话框 -->
    <el-dialog :title="title" :visible.sync="openInsert" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <!--        <el-form-item label="患者Id" prop="patientId">-->
        <!--          <el-input v-model="form.patientId" placeholder="请输入患者Id"/>-->
        <!--        </el-form-item>-->
        <!--        <el-form-item label="医生Id" prop="doctorId">-->
        <!--          <el-input v-model="form.doctorId" placeholder="请输入医生Id"/>-->
        <!--        </el-form-item>-->
        <el-form-item label="患者姓名" prop="userName">
          <el-autocomplete
            popper-class="my-autocomplete"
            class="inline-input"
            v-model="form.patientName"
            :fetch-suggestions="querySearchAsyncForPatient"
            placeholder="请输入患者姓名"
            @blur="handleBlurForPatient(form.patientName)"
            @select="handleSelectForPatient"
          >
            <template slot-scope="{ item }">
              <div class="name">{{ item.value = item.name }}</div>
              <div class="idCard">{{ item.idCard }}</div>
            </template>
          </el-autocomplete>
        </el-form-item>
        <el-form-item label="医生姓名" prop="userName" v-if="false">
          <el-autocomplete
            popper-class="my-autocomplete"
            class="inline-input"
            v-model="form.userName"
            :fetch-suggestions="querySearchAsync"
            placeholder="请输入医生姓名"
            @blur="handleBlur(form.userName)"
            @select="handleSelect"
          >
            <template slot-scope="{ item }">
              <div class="name">{{ item.value = item.userName }}</div>
              <div class="idCard">{{ item.idCard }}</div>
            </template>
          </el-autocomplete>
        </el-form-item>
        <el-form-item label="处方信息" prop="prescriptionInfo">
          <el-input v-model="form.prescriptionInfo" placeholder="请输入处方信息" type="textarea"/>
        </el-form-item>
        <el-form-item label="用法说明" prop="prescriptionUsage">
          <el-input v-model="form.prescriptionUsage" placeholder="请输入用法说明" type="textarea"/>
        </el-form-item>
        <div v-for="(item,i) in drugList1">
          <el-form-item label="药品:" prop="name">
            <!-- <el-input v-model="drugList1[i].name" clearable placeholder="名称"></el-input> -->
            <el-autocomplete
            popper-class="my-autocomplete"
            class="inline-input"
            v-model="drugList1[i].name"
            :fetch-suggestions="querySearchAsyncForDrug"
            placeholder="请输入药品名称"

            @blur="handleBlurForDrug(drugList1[i].name)"
            @select="handleSelectForDrug"
          >
            <template slot-scope="{ item }">
              <div class="name">{{ item.value = item.name }}</div>
              <div class="validity">有效期：{{ item.validity }}</div>
            </template>
          </el-autocomplete>
          </el-form-item>
          <el-form-item label="数量:" prop="number">
            <el-input v-model="drugList1[i].num" clearable placeholder="数量"></el-input>
          </el-form-item>
          <el-button circle icon="el-icon-plus" @click="addList()"></el-button>
          <el-button circle icon="el-icon-minus" @click="subList(i)" v-if="i>0"></el-button>
        </div>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 修改处方管理对话框 -->
    <el-dialog :title="title" :visible.sync="openUpdate" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <!--        <el-form-item label="患者Id" prop="patientId">-->
        <!--          <el-input v-model="form.patientId" placeholder="请输入患者Id"/>-->
        <!--        </el-form-item>-->
        <!--        <el-form-item label="医生Id" prop="doctorId">-->
        <!--          <el-input v-model="form.doctorId" placeholder="请输入医生Id"/>-->
        <!--        </el-form-item>-->
        <el-form-item label="患者姓名"  prop="patientName">
          <el-input disabled v-model="form.patientName"/>
        </el-form-item>
        <el-form-item label="医生姓名" prop="doctorName">
          <el-input disabled v-model="form.doctorName"/>
        </el-form-item>
        <el-form-item label="处方信息" prop="prescriptionInfo">
          <el-input v-model="form.prescriptionInfo" placeholder="请输入处方信息" type="textarea"/>
        </el-form-item>
        <el-form-item label="用法说明" prop="prescriptionUsage">
          <el-input v-model="form.prescriptionUsage" placeholder="请输入用法说明" type="textarea"/>
        </el-form-item>
        <div v-for="(item,i) in drugList1">
          <el-form-item label="药品:" prop="name">
            <el-input    v-model="drugList1[i].name" clearable placeholder="名称"></el-input>
          </el-form-item> 
          <el-form-item label="数量:" prop="number">
            <el-input   v-model="drugList1[i].num" clearable placeholder="数量"></el-input>
          </el-form-item>
          <el-button circle icon="el-icon-plus" @click="addList()"></el-button>
          <el-button circle icon="el-icon-minus" @click="subList(i)" v-if="i>0"></el-button>
        </div>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 药品管理详细信息弹窗 -->
    <el-dialog
      :title="title"
      :visible.sync="open2"
      width="500px"
      class="dialogLand"
      append-to-body
    >
      <el-table v-loading="loading" :data="drugList">
        <el-table-column label="药品名称" align="left" prop="name"/>
        <el-table-column label="药品数量" align="left" prop="num"/>
      </el-table>
    </el-dialog>
  </div>
</template>
<style lang="scss">
.my-autocomplete {
  li {
    line-height: normal;
    padding: 7px;

    .name {
      text-align: center;
      text-overflow: ellipsis;
      overflow: hidden;
    }

    .idCard {
      text-align: center;
      font-size: 12px;
      color: #b4b4b4;
    }

    .highlighted .idCard {
      text-align: center;
      color: #ddd;
    }
    .validity {
      text-align: center;
      font-size: 12px;
      color: #b4b4b4;
    }

    .highlighted .validity {
      text-align: center;
      color: #ddd;
    }
  }
}
</style>
<script>
import {
  listPrescription,
  getPrescription,
  delPrescription,
  addPrescription,
  updatePrescription,
  getDrugNameAndPrice
} from '@/api/prescription/prescription'
import { getDoctorNameAndId } from '@/api/doctorinfo/doctorinfo'
import { getPatientNameAndId } from '@/api/patient/patient'
import { listDrugAndValidity } from '@/api/drug/drug'

export default {
  name: 'Prescription',
  data() {
    return {
      drugList1: [
        {
          name: '',
          num: null,
          nameError: false,
          numError: false
        }
      ],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 处方管理表格数据
      prescriptionList: [],
      // 药品详细表格数据
      drugList: {},
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      openInsert: false,
      openUpdate: false,
      //药品详情弹出层
      open2: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        patientName: null,
        doctorName: null,
        drugList: null,
        prescriptionInfo: null,
        prescriptionUsage: null
      },
      //药品列表和有效期
      drugListAndValidity: [],
      // 医生姓名和id
      doctorNameAndId: [],
      // 患者姓名和id
      patientNameAndId: [],
      // 表单参数
      form: {
        drugList: {}
      },
      // 表单校验
      rules: {}
    }
  },
  created() {
    this.getList()
    this.getDoctor()
    this.getPatient()
    this.getDrugListAndValidity()
  },
  methods: {
    addList() {
      this.drugList1.push({ name: '', num: null })
    },
    //减号
    subList(index) {
      this.drugList1.splice(index, 1)
    },
    /** 查询药品列表 */
    getDrugListAndValidity() {
      listDrugAndValidity(this.queryParams).then(response => {
        console.log('response', response)
        this.drugListAndValidity = response.data
        console.log('this.drugListAndValidity', this.drugListAndValidity)
      })
    },
    /** 查询医生姓名和id */
    getDoctor() {
      getDoctorNameAndId().then(response => {
        this.doctorNameAndId = response.data
        console.log('this.doctorNameAndId', this.doctorNameAndId)
      })
    },
    /** 查询患者姓名和id */
    getPatient() {
      getPatientNameAndId().then(response => {
        this.patientNameAndId = response.data
        console.log('this.patientNameAndId', this.patientNameAndId)
      })
    },
    /** 查询处方管理列表 */
    getList() {
      this.loading = true;
      listPrescription(this.queryParams).then(response => {
        this.prescriptionList = response.rows;
        this.total = response.total;
        this.loading = false;
        console.log(this.prescriptionList)
      });
    },
    // 取消按钮
    cancel() {
      this.openInsert = false;
      this.openUpdate = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        createTime: null,
        createUser: null,
        updateTime: null,
        updateUser: null,
        isDeleted: null,
        patientName: null,
        doctorName: null,
        drugList: {},
        prescriptionInfo: null,
        prescriptionUsage: null
      }
      this.resetForm('form')
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm')
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.drugList1=[{
        name: '',
        num: null,
        nameError: false,
        numError: false
      }];
      this.openInsert = true;
      this.title = "添加处方管理";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getPrescription(id).then(response => {
        this.form = response.data;
        this.openUpdate = true;
        this.title = "修改处方管理";
      })
      getDrugNameAndPrice(id).then(response => {
        console.log(response.data);
        this.drugList1=response.data;
      });
      ;
    },
    /**
     * 药品数组详情
     * @param {*} row
     */
    handleLandClick(row) {
      this.drugList = null
      this.open2 = true
      this.title = '药品数组详情'
      getDrugNameAndPrice(row.id).then(response => {
        this.drugList = response.data
        console.log(this.drugList)
      })

    },
    /** 提交按钮 */
    submitForm() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            let param = {}
            param.drugList = this.drugList1
            param.doctorId = this.form.doctorId
            param.patientId = this.form.patientId
            param.prescriptionInfo = this.form.prescriptionInfo
            param.prescriptionUsage = this.form.prescriptionUsage
            param.id = this.form.id
            updatePrescription(param).then(response => {
              this.$modal.msgSuccess('修改成功')
              this.openUpdate = false
              this.getList()
            })
          } else {
            let param = {}
            param.drugList = this.drugList1
            param.doctorId = this.form.doctorId
            param.patientId = this.form.patientId
            param.prescriptionInfo = this.form.prescriptionInfo
            param.prescriptionUsage = this.form.prescriptionUsage
            //只要有一个名字为空，flag就为false
            let flagName = this.drugList1.every(item => !!item.name)
            let flagNum  = this.drugList1.every(item => !!item.num)
            if(flagName){
              if(flagNum){
                //不为空状态
              this.nameError = true;
              this.numError  = true;
              addPrescription(param).then(response => {
              this.$modal.msgSuccess('新增成功')
              this.openInsert = false
              this.getList()
              return;
            })}else{
            alert("药品数量不能为空")}
            }else{
            alert("药品名字不能为空")}
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids
      this.$modal.confirm('是否确认删除处方管理编号为"' + ids + '"的数据项？').then(function() {
        return delPrescription(ids)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess('删除成功')
      }).catch(() => {
      })
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('prescription/prescription/export', {
        ...this.queryParams
      }, `prescription_${new Date().getTime()}.xlsx`)
    },
    handleBlur(val) {
      console.log('input Input value:', val)
      console.log('Doctor names:', this.doctorNameAndId.map(user => user.userName))
      const selectedUser = this.doctorNameAndId.find(user => user.userName === val)
      const id = selectedUser ? selectedUser.userId : null
      this.form.doctorId = id
      console.log('input Selected id:', id)
    },
    handleSelect(val) {
      console.log('select Input value:', val)
      console.log('Doctor idCard:', this.doctorNameAndId.map(user => user.idCard))
      this.form.doctorId = val.userId
      this.form.userName = val.userName
      console.log('select Selected id:', this.form.doctorId)
    },
    handleBlurForPatient(val) {
      console.log('input Input value:', val)
      console.log('Patient names:', this.patientNameAndId.map(user => user.name))
      const selectedUser = this.patientNameAndId.find(user => user.name === val)
      const id = selectedUser ? selectedUser.id : null
      this.form.patientId = id
      console.log('input Selected id:', id)
    },
    handleSelectForPatient(val) {
      console.log('select Input value:', val)
      console.log('Doctor idCard:', this.patientNameAndId.map(user => user.idCard))
      this.form.patientId = val.id
      console.log('select Selected id:', this.form.patientId)
    },
    handleBlurForDrug(val) {
      console.log(val)
      const selectedDrug = this.drugListAndValidity.find(user => user.name === val)
      const name = selectedDrug ? selectedDrug.name : null
      this.form.drugList.name = name
    },
    handleSelectForDrug(val) {
      console.log(val)
      this.form.drugList.name = val.value
    },
    querySearchAsync(queryString, cb) {
      const restaurants = this.doctorNameAndId
      const results = queryString ? restaurants.filter(this.createStateFilter(queryString)) : restaurants

      // console.log('results', results)
      cb(results)
    },
    querySearchAsyncForPatient(queryString, cb) {
      const restaurants = this.patientNameAndId
      const results = queryString ? restaurants.filter(this.createStateFilter(queryString)) : restaurants

      // console.log('results', results)
      cb(results)
    },
    querySearchAsyncForDrug(queryString, cb) {
      const restaurants = this.drugListAndValidity
      const results = queryString ? restaurants.filter(this.createStateFilter(queryString)) : restaurants

      // console.log('results', results)
      cb(results)
    },
    createStateFilter(queryString) {
      return (state) => {
        return (state.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0)
      }
    }
  }
};
</script>
